import { Effect, Reducer } from 'umi';
import { message } from 'antd';
import { ParamItem } from '@/pages/System/Param/data';
import { fetchAllParam, addParam, updateParam, deleteParams } from '@/services/paramApis';
import { TradeResult } from './connect';

export interface ParamModelState {
  rows?: ParamItem[];
  total?: number;
  pageSize?: number;
}

export interface ParamModelType {
  namespace: 'params';
  state: ParamModelState;
  effects: {
    fetchAllParam: Effect;
    addParam: Effect;
    updateParam: Effect;
    deleteParams: Effect;
  };
  reducers: {
    updateState: Reducer<ParamModelState>;
  };
}

const ParamModel: ParamModelType = {
  namespace: 'params',

  state: {
    rows: [],
    total: 0,
    pageSize: 10,
  },

  effects: {
    *fetchAllParam({ payload }, { call, put }) {
      try {
        console.log(JSON.stringify(payload));
        const response: TradeResult = yield call(fetchAllParam, payload);
        const { success } = response;
        if (success) {
          const { result } = response;
          yield put({ type: 'updateState', payload: result });
        }
      } catch(e) {
        console.info(e);
        message.error('数据获取失败');
      }
    },
    *addParam({ payload }, sagaEffects) {
      const { call } = sagaEffects;
      try {
        console.log(JSON.stringify(payload));
        const response: TradeResult = yield call(addParam, payload);
        const { success } = response;
        if (success) {
          message.success('新增成功');
          return true;
        } else {
          return false;
        }
      } catch(e) {
        console.error(e);
        message.error('新增失败');
        return false;
      }
    },
    *updateParam({ payload }, sagaEffects) {
      const { call } = sagaEffects;
      try {
        console.log(JSON.stringify(payload));
        const response: TradeResult = yield call(updateParam, payload);
        const { success } = response;
        if (success) {
          message.success('更新成功');
          return true;
        } else {
          return false;
        }
      } catch(e) {
        console.error(e);
        message.error('更新失败');
        return false;
      }
    },
    *deleteParams({ payload }, sagaEffects) {
      const { call} = sagaEffects;
      try {
        console.log(JSON.stringify(payload));
        const response: TradeResult = yield call(deleteParams, payload);
        const { success } = response;
        if (success) {
          message.success('删除成功');
          return true;
        } else {
          return false;
        }
      } catch(e) {
        console.error(e);
        message.error('删除失败');
        return false;
      }
    }
  },

  reducers: {
    updateState(state, { payload }) {
      console.info(payload);
      return {
        ...state,
        ...payload
      }
    },
  },
}

export default ParamModel;